package com.javatest.validate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2020-11-10 下午4:15
 */
public class ValidStudentCountConstraintValidator
        implements ConstraintValidator<ValidStudentCount, Room2> {

    @Override
    public void initialize(ValidStudentCount constraintAnnotation) {
    }

    @Override
    public boolean isValid(Room2 room, ConstraintValidatorContext context) {
        if (room == null) {
            return true;
        }
        boolean isValid = false;
        if (room.getStudentNames().size() <= room.getMaxStuNum()) {
            isValid = true;
        }

        // 自定义提示语（当然你也可以不自定义，那就使用注解里的message字段的值）
        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("校验失败xxx")
                    .addPropertyNode("studentNames")
                    .addConstraintViolation();
        }
        return isValid;
    }
}
